package com.book.dao;

import com.book.pojo.Address;
import com.book.pojo.Book;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * author:rengl
 * 2023-04-08 08:07
 * 模拟持久层,纯java状态下从内存中查询List
 */
@Component
public class AddressMapper {

    private List<Address> list = new ArrayList();

    public Integer add(Address address) {
        //设置id,模拟数据库id自增
        address.setId(list.size()==0?1:list.get(list.size()-1).getId()+1);
        list.add(address);
        return 1;
    }
    public List<Address> findAll() {
        return list;
    }

    public List<Address> findByUserId(Integer userId){
        List<Address> userAddressList = new ArrayList<>(  );
        for (Address address : list) {
            if(userId == address.getUserId()){
                userAddressList.add( address );
            }
        }
        return userAddressList;
    }

    public Address findOne(Integer id) {
        for (Address address : list) {
            if(id.equals(address.getId())){
                return address;
            }
        }
        return null;
    }

    public Integer update(Address updateaddress) {
        for (Address address : list) {
            if(address.getId().equals(updateaddress.getId())){
                address.setAddress(updateaddress.getAddress());
                address.setPostal(updateaddress.getPostal());
                address.setUserId(updateaddress.getUserId());
                return 1;
            }
        }
        return 0;
    }


    public Integer delete(Integer id) {
        Iterator<Address> iterator = list.iterator();
        while (iterator.hasNext()){
            Address address = iterator.next();
            if(address.getId().equals(id)){
                iterator.remove();
                return 1;
            }
        }
        return 0;
    }
}
